package com.lucher.mes.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lucher.mes.common.ConfigUtil;
import com.lucher.mes.common.FileToBase64;
import com.lucher.mes.common.Tools;
import com.lucher.mes.dao.PrisonerMapper;
import com.lucher.mes.dao.ProblemMapper;
import com.lucher.mes.dao.ProduceinfoMapper;
import com.lucher.mes.dao.ProduceproductMapper;
import com.lucher.mes.dao.ProducescheduleMapper;
import com.lucher.mes.dao.ProducescheduleproblemMapper;
import com.lucher.mes.dao.ProductMapper;
import com.lucher.mes.dao.ProductworkorderMapper;
import com.lucher.mes.dao.RollcallMapper;
import com.lucher.mes.dao.RollcallinfoMapper;
import com.lucher.mes.dao.ToolinoutMapper;
import com.lucher.mes.dao.ToolplateMapper;
import com.lucher.mes.dao.WorklineMapper;
import com.lucher.mes.dao.WorklinesectionmachineMapper;
import com.lucher.mes.dao.WorkmachineloginMapper;
import com.lucher.mes.dao.WorkorderMapper;
import com.lucher.mes.dao.WorkorderproblemMapper;
import com.lucher.mes.dao.WorksectionMapper;
import com.lucher.mes.po.Prisoner;
import com.lucher.mes.po.Problem;
import com.lucher.mes.po.Produceinfo;
import com.lucher.mes.po.Produceproduct;
import com.lucher.mes.po.Produceschedule;
import com.lucher.mes.po.Producescheduleproblem;
import com.lucher.mes.po.Product;
import com.lucher.mes.po.Productworkorder;
import com.lucher.mes.po.Rollcall;
import com.lucher.mes.po.Rollcallinfo;
import com.lucher.mes.po.Toolinout;
import com.lucher.mes.po.Toolplate;
import com.lucher.mes.po.Workline;
import com.lucher.mes.po.Worklinesectionmachine;
import com.lucher.mes.po.Workmachinelogin;
import com.lucher.mes.po.Workorder;
import com.lucher.mes.po.Workorderproblem;
import com.lucher.mes.po.Worksection;
import com.lucher.mes.service.IProductdepotService;
import com.lucher.mes.service.ISystemparaService;

/**
 * 用户控制层
 */
@Controller
@Scope("prototype")
@RequestMapping("/httpForMps")
public class HttpForMpsController extends BaseController {
	@Autowired
    private DataSourceTransactionManager txManager;
	@Autowired
	private PrisonerMapper prisonerDao;
	@Autowired
	private WorklinesectionmachineMapper worklinesectionmachineDao;
	@Autowired
	private WorklineMapper worklineDao;
	@Autowired
	private WorksectionMapper worksectionDao;
	@Autowired
	private ProduceinfoMapper produceinfoDao;
	@Autowired
	private WorkmachineloginMapper workmachineloginDao;
	@Autowired
	private ISystemparaService systemparaService;
	@Autowired
	private ProduceproductMapper produceproductDao;
	@Autowired
	private WorkorderMapper workorderDao;
	@Autowired
	private ProductworkorderMapper productworkoerderDao;
	@Autowired
	private WorkorderproblemMapper workorderproblemDao;
	@Autowired
	private IProductdepotService productdepotService;
	@Autowired
	private ProductworkorderMapper productworkorderrDao;
	@Autowired
	private ProducescheduleMapper producesheduleDao;
	@Autowired
	private ProducescheduleproblemMapper producescheduleproblemDao;
	@Autowired
	private ProductworkorderMapper productworkorderDao;
	@Autowired
	private ProductMapper productDao;
	@Autowired
	private ProblemMapper problemDao;
	@Autowired
	private RollcallMapper rollcallDao;
	@Autowired
	private RollcallinfoMapper rollcallinfoDao;
	@Autowired
	private ToolplateMapper toolplateDao;
	@Autowired
	private ToolinoutMapper toolinoutDao;
	
	/*
     * 特殊的instance变量
     * 注：零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：
     * 生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码。
     */
    private static byte[] lock = new byte[0];   
	
    
    @ResponseBody
	@RequestMapping(value = "/commServer")
	// 销售服务器请求总接口
	// http://localhost:8080/shenfu/httpForMps/commServerForMPS?methodname=?&parajson={}
	public Map<String, Object> commServer(HttpServletRequest request) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String parajson = Tools.getStr(request.getParameter("parajson"));
		JSONObject jsonObj = null;
		try{
			
			jsonObj = new JSONObject(parajson);
			String method = Tools.getStr(jsonObj.getString("method"));
			if("pushPrisonList".equals(method)){//推送犯人信息
				/***************** 封装userbusiness主表 ******************/
				return pushPrisonList(jsonObj);
			} else if("userLogin".equals(method)){//终端账号密码登录
				/***************** 封装userbusiness主表 ******************/
				return saveUserLogin(jsonObj);
			} else if("uploadfingerprint".equals(method)){//上传指纹信息
				/***************** 封装userbusiness主表 ******************/
				return saveUploadfingerprint(jsonObj);
			}else if("getpackagedataByNfcid".equals(method)){//获取NFC卡包信息
				/***************** 封装userbusiness主表 ******************/
				return getpackagedataByNfcid(jsonObj);
			}else if("getpackagedataBySn".equals(method)){//获取NFC卡包信息
				/***************** 封装userbusiness主表 ******************/
				return getpackagedataBySn(jsonObj);
			} else if("saveUploaddisqualityByNfcid".equals(method)){//上传质检信息
				/***************** 封装userbusiness主表 ******************/
				return saveUploaddisqualityByNfcid(jsonObj);
			}else if("saveUploaddisqualityBySn".equals(method)){//上传质检信息
				/***************** 封装userbusiness主表 ******************/
				return saveUploaddisqualityBySn(jsonObj);
			} else if("getconditioncfg".equals(method)){//上传质检信息
				/***************** 封装userbusiness主表 ******************/
				return getconditioncfg(jsonObj);
			} else if("gethistoryrecords".equals(method)){//上传质检信息
				/***************** 封装userbusiness主表 ******************/
				return gethistoryrecords(jsonObj);
			} else if("getSn".equals(method)){//上传质检信息
				/***************** 封装userbusiness主表 ******************/
				return getSn(jsonObj);
			} else if("exit".equals(method)){//退出
				/***************** 封装userbusiness主表 ******************/
				return exit(jsonObj);
			}else if("findBigscreanshowData".equals(method)){//
				/***************** 封装userbusiness主表 ******************/
				return findBigscreanshowData(jsonObj);
			}else if("findSmallscreanshowData".equals(method)){//
				/***************** 封装userbusiness主表 ******************/
				return findSmallscreanshowData(jsonObj);
			}else if("uploadRollcallinfo".equals(method)){//上传点名签到信息
				/***************** 封装userbusiness主表 ******************/
				return saveUploadRollcallinfo(jsonObj);
			}else if("borrowTool".equals(method)){//上传点名签到信息
				/***************** 封装userbusiness主表 ******************/
				return saveBorrowTool (jsonObj);
			}else if("returnTool".equals(method)){//上传点名签到信息
				/***************** 封装userbusiness主表 ******************/
				return saveReturnTool  (jsonObj);
			} else {
				responseMap.put("code", "201");//-请输入正确的请求格式
				responseMap.put("message", "请输入正确的请求方法名称");
				responseMap.put("data", dataMap);
				return responseMap;
			}
		}catch(Exception e){
			e.printStackTrace();
			responseMap.put("code", "201");//-请输入正确的JSON请求格式
			responseMap.put("message", "请输入正确的JSON请求格式");//-
			responseMap.put("data", dataMap);
			return responseMap;
		}
	}
	
	// 操作员登录
	// http://115.159.71.126:8080/shenfu/httpForMps/commServerForSaleMPS?methodname=operatorLogin&parajson={"user_phone":"123456789","password":"123456"}
	public Map<String, Object> pushPrisonList(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("status", "1");
		
		String addtime = Tools.getCurrentTime();
		// 判断是否单点登录（不允许同一个操作员登录同时在俩个客户端在线）
		String prisoner_password = ConfigUtil.getConfigFilePath("prisoner_password", "system.properties");
		
		//依次增加新的仓位
		ArrayList<Prisoner> prisonerList = new ArrayList<Prisoner>();
		//合同信号列表
		JSONArray prisonerJSONList = jsonObj.getJSONArray("prisonlist");
		if(prisonerJSONList != null){
			for (int i = 0; i < prisonerJSONList.length(); i++) {
				JSONObject prisonerObject = prisonerJSONList.getJSONObject(i);
				Prisoner prisoner  = new Prisoner();
				prisoner.setAddtime(addtime);
				prisoner.setStatus("入狱");
				prisoner.setPassword(prisoner_password);
				prisoner.setPrisonercode(Tools.getStr(prisonerObject.getString("prisonercode")));
				prisoner.setPrisonername(Tools.getStr(prisonerObject.getString("prisonername")));
				prisoner.setCrimename(Tools.getStr(prisonerObject.getString("crimename")));
				prisoner.setNation(Tools.getStr(prisonerObject.getString("nation")));
				prisoner.setNativeplace(Tools.getStr(prisonerObject.getString("nativeplace")));
				prisoner.setAge(Tools.getStr(prisonerObject.getString("age")));
				prisoner.setPrisonterm(Tools.getStr(prisonerObject.getString("prisonterm")));
				prisoner.setLeftprisonterm(Tools.getStr(prisonerObject.getString("leftprisonterm")));
				prisoner.setMajorcriminals(Tools.getStr(prisonerObject.getString("majorcriminals")));
				prisoner.setPrisonlevel(Tools.getStr(prisonerObject.getString("prisonlevel")));
				prisoner.setPrisontime(Tools.getStr(prisonerObject.getString("prisontime")));
				prisoner.setHeadfilepath(Tools.getStr(prisonerObject.getString("headfilepath")));
				prisoner.setFingerfilepath(Tools.getStr(prisonerObject.getString("fingerfilepath")));
				prisonerList.add(prisoner);
			}
			
			prisonerDao.saveBatch(prisonerList);
			
			responseMap.put("status", "1");//保存失败
			responseMap.put("result", "操作成功");//上传合同失败
			return responseMap;
			
		} else {
			responseMap.put("status", "0");//
			responseMap.put("result", "操作为空");//
		}
		
		
		return responseMap;
	}

	// 操作员登录
	// http://115.159.71.126:8080/shenfu/httpForMps/commServerForSaleMPS?methodname=operatorLogin&parajson={"user_phone":"123456789","password":"123456"}
	public Map<String, Object> saveUserLogin(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		responseMap.put("message", "登录成功");
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String prisonercode = Tools.getStr(jsonObj.getString("prisonercode"));
		String password = Tools.getStr(jsonObj.getString("password"));
		String machinecode = Tools.getStr(jsonObj.getString("machinecode"));
		//封装登录信息
		Prisoner record = new Prisoner();
		record.setPrisonercode(prisonercode);
		Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(record);
		
		if(prisoner == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "登录账号错误");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		if(!password.equals(prisoner.getPassword())){
			responseMap.put("code", "201");//登录密码错误
			responseMap.put("message", "登录密码错误");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		//查询工位机
		Worklinesectionmachine relation = worklinesectionmachineDao.findByMachinecode(machinecode);
		if(relation == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "该工位机未在产线上");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		Workline line = worklineDao.findByCode(relation.getLinecode());
		if(line == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "该生产线不存在");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		Worksection section = worksectionDao.findByCode(relation.getSectioncode());
		if(section == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "该工段不存在");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		//保存登录信息
		Workmachinelogin workmachinelogin = new Workmachinelogin();
		workmachinelogin.setMachinecode(machinecode);
		workmachinelogin.setPrisonercode(prisonercode);
		workmachinelogin.setPrisonername(prisoner.getPrisonername());
		workmachinelogin.setAddtime(Tools.getCurrentTime());
		workmachineloginDao.insertSelective(workmachinelogin);
		
		dataMap.put("token", prisonercode);
		// 封装用户信息
		HashMap<String, Object> employeeMap = new HashMap<String, Object>();
		employeeMap.put("linecode", Tools.getStr(line.getCode()));
		employeeMap.put("linname", Tools.getStr(line.getName()));
		employeeMap.put("headfilepath", Tools.getStr(prisoner.getHeadfilepath()));
		employeeMap.put("fingerfilepath", FileToBase64.encodeBase64File(Tools.getStr(prisoner.getFingerfilepath())));
		employeeMap.put("prisonname", Tools.getStr(prisoner.getPrisonername()));
		employeeMap.put("prisonercode", Tools.getStr(prisoner.getPrisonercode()));
		employeeMap.put("sectioncode", Tools.getStr(section.getCode()));
		employeeMap.put("sectionname", Tools.getStr(section.getName()));
		dataMap.put("employeeinfo", employeeMap);
		responseMap.put("data", dataMap);
		
		return responseMap;
	}
	
	/**
	 * 图片下载
	 */
	@RequestMapping(value = "/getImgOrFileDownload")
	public Map<String, Object> getImgOrFileDownload(String filepath,HttpServletResponse response){
		
		if(StringUtils.isEmpty(filepath)){
			return null;
		}
		
		//门锁图片
        try {
			File excelTemplate = new File(filepath);
			response.reset();
			
			//图片文件，直接在页面显示图片
			//if (Tools.isImage(excelTemplate)) {
			Boolean flag = false;
			if (flag) {
				response.setHeader("Accept-Ranges", "bytes");  
	            response.setHeader("Pragma", "no-cache");  
	            response.setHeader("Cache-Control", "no-cache");  
	            response.setDateHeader("Expires", 0);  
			}else{//非图片文件，先下载
				response.setContentType("application/octet-stream");
				response.addHeader("Content-Length", "" + excelTemplate.length()); // 文件大小
				response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(Tools.getNowRandomTwo(), "UTF-8"));
			}
			
			FileInputStream fis = new FileInputStream(excelTemplate);
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[1024 * 1024];
			while (fis.read(buffer) > 0) {
				toClient.write(buffer);
			}
			fis.close();
			toClient.flush();
			toClient.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
    }
	
	// 上传指纹
	public Map<String, Object> saveUploadfingerprint(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String prisonercode = Tools.getStr(jsonObj.getString("token"));
		String fingerprintbase64list = Tools.getStr(jsonObj.getString("fingerprintbase64list"));
		//封装登录信息
		Prisoner record = new Prisoner();
		record.setPrisonercode(prisonercode);
		Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(record);
		
		if(prisoner == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "人员编号错误");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		//保存指纹信息
		//String path = request.getServletContext().getRealPath("/upload/");
        String upload_file_path = systemparaService.findSystemParaByCodeStr("upload_file_path");
        String folderpath = upload_file_path + File.separatorChar + "fingerfile";
		File folder = new File(folderpath);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		
		String fingerfilepath = folderpath + File.separatorChar + Tools.getNowRandomTwo() + ".bin";
		FileToBase64.decoderBase64File(fingerprintbase64list, fingerfilepath);
		
		//修改犯人指纹文件保存路径
		prisoner.setFingerfilepath(fingerfilepath);
		prisonerDao.updateByPrimaryKeySelective(prisoner);
		
		responseMap.put("code", "200");
		responseMap.put("message", "上传数据成功");
		responseMap.put("data", dataMap);
		
		return responseMap;
	}
	
	//指纹打卡
	public Map<String, Object> saveUploadcheckon(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String prisonercode = Tools.getStr(jsonObj.getString("prisonercode"));
		
		//封装登录信息
		Prisoner record = new Prisoner();
		record.setPrisonercode(prisonercode);
		Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(record);
		
		if(prisoner == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "人员编号错误");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		responseMap.put("code", "200");
		responseMap.put("message", "指纹打卡成功");
		responseMap.put("data", dataMap);
		
		return responseMap;
	}
	
	//根据NFCID获取包信息
	public Map<String, Object> getpackagedataByNfcid(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		responseMap.put("message", "获取数据成功");
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String prisonercode = Tools.getStr(jsonObj.getString("token"));
		String nfcid = Tools.getStr(jsonObj.getString("nfcid"));
		
		//封装登录信息
		Prisoner record = new Prisoner();
		record.setPrisonercode(prisonercode);
		Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(record);
		if(prisoner == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "人员编号错误");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		//查询该nfc对应的生产包信息
		Produceproduct produceproduct = produceproductDao.findByNfcid(nfcid);
		if(produceproduct == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "该卡未绑定任何产品包信息");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		List<HashMap<String, Object>> checkdataList = new ArrayList<HashMap<String, Object>>();
		for (int i = 1; i <= produceproduct.getDepotamount(); i++) {
			HashMap<String, Object> packMap = new HashMap<String, Object>();
			packMap.put("number", produceproduct.getBatchno());
			packMap.put("productname", produceproduct.getProductname());
			packMap.put("productcode", produceproduct.getProductcode());
			packMap.put("sn", produceproduct.getBatchno());
			packMap.put("package", String.valueOf(i));//件数
			checkdataList.add(packMap);
		}
		
		dataMap.put("checkdata", checkdataList);
		
		//查询产品对应的工序信息
		List<HashMap<String, Object>> disqualtypeList = new ArrayList<HashMap<String, Object>>();
		
		Productworkorder productworkorderDemo = new Productworkorder();
		productworkorderDemo.setProductcode(produceproduct.getProductcode());
		productworkorderDemo.setSort("serialnumber");
		productworkorderDemo.setOrder("asc");
		List<Productworkorder> productworkorderlist = productworkoerderDao.findByList(productworkorderDemo);
		for (Productworkorder productworkorder : productworkorderlist) {
			HashMap<String, Object> orderMap = new HashMap<String, Object>();
			orderMap.put("ordercode", productworkorder.getOrdercode());
			orderMap.put("ordername", productworkorder.getOrdername());
			
			Workorderproblem WorkorderproblemDemo = new Workorderproblem();
			WorkorderproblemDemo.setOrdercode(productworkorder.getOrdercode());
			List<Workorderproblem> workorderproblemList =  workorderproblemDao.findByList(WorkorderproblemDemo);
			List<HashMap<String, Object>> problemList = new ArrayList<HashMap<String, Object>>();
			for (Workorderproblem workorderproblem : workorderproblemList) {
				HashMap<String, Object> problemMap = new HashMap<String, Object>();
				problemMap.put("code", workorderproblem.getProblemcode());
				problemMap.put("name", workorderproblem.getProblemname());
				problemList.add(problemMap);
			}
			orderMap.put("problem", problemList);
			disqualtypeList.add(orderMap);
		}
		
		dataMap.put("disqualtype", disqualtypeList);
		
		responseMap.put("data", dataMap);
		
		return responseMap;
	}
	
	//根据SN码获取包信息
	public Map<String, Object> getpackagedataBySn(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		responseMap.put("message", "获取数据成功");
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String prisonercode = Tools.getStr(jsonObj.getString("token"));
		String sn = Tools.getStr(jsonObj.getString("sn"));
		
		//封装登录信息
		Prisoner record = new Prisoner();
		record.setPrisonercode(prisonercode);
		Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(record);
		if(prisoner == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "人员编号错误");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		//查询该nfc对应的生产包信息
		Produceproduct produceproduct = produceproductDao.findByBatchno(sn);
		if(produceproduct == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "该SN码不存在");//
			responseMap.put("data", dataMap);
			return responseMap;
		}
		
		List<HashMap<String, Object>> checkdataList = new ArrayList<HashMap<String, Object>>();
		for (int i = 1; i <= produceproduct.getDepotamount(); i++) {
			HashMap<String, Object> packMap = new HashMap<String, Object>();
			packMap.put("number", produceproduct.getBatchno());
			packMap.put("productname", produceproduct.getProductname());
			packMap.put("productcode", produceproduct.getProductcode());
			packMap.put("sn", produceproduct.getBatchno());
			packMap.put("package", String.valueOf(i));//件数
			checkdataList.add(packMap);
		}
		
		dataMap.put("checkdata", checkdataList);
		
		//查询产品对应的工序信息
		List<HashMap<String, Object>> disqualtypeList = new ArrayList<HashMap<String, Object>>();
		
		Productworkorder productworkorderDemo = new Productworkorder();
		productworkorderDemo.setProductcode(produceproduct.getProductcode());
		productworkorderDemo.setSort("serialnumber");
		productworkorderDemo.setOrder("asc");
		List<Productworkorder> productworkorderlist = productworkoerderDao.findByList(productworkorderDemo);
		for (Productworkorder productworkorder : productworkorderlist) {
			HashMap<String, Object> orderMap = new HashMap<String, Object>();
			orderMap.put("ordercode", productworkorder.getOrdercode());
			orderMap.put("ordername", productworkorder.getOrdername());
			
			Workorderproblem WorkorderproblemDemo = new Workorderproblem();
			WorkorderproblemDemo.setOrdercode(productworkorder.getOrdercode());
			List<Workorderproblem> workorderproblemList =  workorderproblemDao.findByList(WorkorderproblemDemo);
			List<HashMap<String, Object>> problemList = new ArrayList<HashMap<String, Object>>();
			for (Workorderproblem workorderproblem : workorderproblemList) {
				HashMap<String, Object> problemMap = new HashMap<String, Object>();
				problemMap.put("code", workorderproblem.getProblemcode());
				problemMap.put("name", workorderproblem.getProblemname());
				problemList.add(problemMap);
			}
			orderMap.put("problem", problemList);
			disqualtypeList.add(orderMap);
		}
		
		dataMap.put("disqualtype", disqualtypeList);
		
		responseMap.put("data", dataMap);
		
		return responseMap;
	}
	
	
	//上传质检不合格产品通过NFCID
	public Map<String, Object> saveUploaddisqualityByNfcid(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		responseMap.put("message", "获取数据成功");
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		//加锁
		synchronized(lock) {
			//获取配置的事务信息
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
			TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
			
			try{
				//质检员
				String prisonercode = Tools.getStr(jsonObj.getString("token"));
				String nfcid = Tools.getStr(jsonObj.getString("nfcid"));
				
				//当前时间
				String currentTime =  Tools.getCurrentTime();
				//查询生产人员
				Prisoner prisoner = new Prisoner();
				prisoner.setPrisonercode(prisonercode);
				prisoner = prisonerDao.findPrisonerByPrisonercode(prisoner);
				if(prisoner == null){
					//回滚
					txManager.rollback(status);
					responseMap.put("code", "201");//
					responseMap.put("message", "该质检人员不存在");//
					responseMap.put("data", dataMap);
					return responseMap;
				}
				
				//查询生产产品信息
				Produceproduct produceproduct = produceproductDao.findByNfcid(nfcid);
				if(produceproduct == null){
					//回滚
					txManager.rollback(status);
					responseMap.put("code", "201");//
					responseMap.put("message", "该NFC卡号未绑定任何产品信息");//
					responseMap.put("data", dataMap);
					return responseMap;
				}
				
				if(!"生产中".equals(produceproduct.getProductstatus()) && ! "待返工".equals(produceproduct.getProductstatus())){
					//回滚
					txManager.rollback(status);
					responseMap.put("code", "201");//
					responseMap.put("message", "该NFC卡号绑定的产品不是生产状态，不能进行质检!");//
					responseMap.put("data", dataMap);
					return responseMap;
				}
				
				//查询产线信息
				Produceinfo produceinfo = produceinfoDao.findByProducecode(produceproduct.getProducecode());
				if(produceinfo == null){
					//回滚
					txManager.rollback(status);
					responseMap.put("code", "201");//
					responseMap.put("message", "该NFC卡号关联的产线不存在");//
					responseMap.put("data", dataMap);
					return responseMap;
				}
				
				//封装质检不合格产品工序问题LIST,批量插入数据用
				ArrayList<Producescheduleproblem> producescheduleproblemList = new ArrayList<Producescheduleproblem>();
				//封装正常产品的工序LIST,批量插入数据用
				ArrayList<Produceschedule> producescheduleList = new ArrayList<Produceschedule>();
				
				//封装有问题的工位机
				ArrayList<Worklinesectionmachine> worklinesectionmachineList_problem = new ArrayList<Worklinesectionmachine>();
				
				//该包原来的总件数
				int leftdepotamount = produceproduct.getDepotamount();
				//质量信息
				JSONObject disqualitydataObject = jsonObj.getJSONObject("disqualitydata");
				//产品问题
				JSONArray datalistArray = disqualitydataObject.getJSONArray("datalist");
				
				//有质量问题的包数
				int qualityNum = 0;
				
				//有质量问题的产品,必须要重新分包
				if(datalistArray != null && datalistArray.length() > 0){
					//有质量问题的包数
					qualityNum = datalistArray.length();
					//正常产品数量
					leftdepotamount = leftdepotamount - qualityNum;
						
					//循环有问题的产品包数
					for (int i = 0; i < qualityNum; i++) {
						JSONObject disqualityinfo = datalistArray.getJSONObject(i);
						
						//String packagenum = Tools.getStr(disqualityinfo.getString("package"));
						//String disqualitynumber = Tools.getStr(disqualityinfo.getString("disqualitynumber"));
						String sn = Tools.getStr(disqualityinfo.getString("sn"));
						
						//将有问题的产品拆分入库
						//String batchno = productdepotService.getProductbatchno(produceproduct.getProductcode());
						Produceproduct produceproductProblem = new Produceproduct();
						produceproductProblem.setProducecode(produceproduct.getProducecode());
						produceproductProblem.setProductcode(produceproduct.getProductcode());
						produceproductProblem.setProductname(produceproduct.getProductname());
						produceproductProblem.setBatchno(sn);
						produceproductProblem.setDepotamount(1);
						produceproductProblem.setProductstatus("待返工");
						produceproductProblem.setPrintflag("未打印");
						produceproductProblem.setAddtime(produceproduct.getAddtime());
						produceproductProblem.setNfcid(null);
						produceproductProblem.setCheckdata(null);
						produceproductProblem.setCheckercode(null);
						produceproductProblem.setCheckername(null);
						produceproductDao.insert(produceproductProblem);
						
						//问题列表
						JSONArray disqualityproblem = disqualityinfo.getJSONArray("disqualityproblem");
						
						for (int j = 0; j < disqualityproblem.length(); j++) {
							JSONObject orderinfo = disqualityproblem.getJSONObject(j);
							String ordercode = Tools.getStr(orderinfo.getString("ordercode"));
							String ordername = Tools.getStr(orderinfo.getString("ordername"));
							
							//查找该工序对应的位置
							Productworkorder productworkorder = new Productworkorder();
							productworkorder.setProductcode(produceinfo.getProductcode());
							productworkorder.setOrdercode(ordercode);
							productworkorder = productworkorderDao.findByProductcodeAndOrdercode(productworkorder);
							
							if(productworkorder != null){
								//查询该工序对应的工位机
								Worklinesectionmachine worklinesectionmachineDemo = new Worklinesectionmachine();
								worklinesectionmachineDemo.setLinecode(produceinfo.getLinecode());
								worklinesectionmachineDemo.setSerialnumber(productworkorder.getSerialnumber());
								worklinesectionmachineDemo = worklinesectionmachineDao.findByLinecodeAndSerialnumber(worklinesectionmachineDemo);
								if(worklinesectionmachineDemo != null){
									
									//将有问题的工位机保存到临时缓存中，后面单独处理
									worklinesectionmachineList_problem.add(worklinesectionmachineDemo);
									
									//查询每个工序对应的当前生产人员
									Workmachinelogin workmachinelogin = workmachineloginDao.findLatestLoginerByMachinecode(worklinesectionmachineDemo.getMachinecode());
									if(workmachinelogin == null){
										//回滚
					 					txManager.rollback(status);
					 					responseMap.put("code", "201");//
					 					responseMap.put("message", "产线上还有工位机未登陆过");
					 					responseMap.put("data", dataMap);
					 					return responseMap;
									}
									//问题列表
									JSONArray problemArray = orderinfo.getJSONArray("problem");
									for (int k = 0; k < problemArray.length(); k++) {
										JSONObject problemObject = problemArray.getJSONObject(k);
										String problemcode = Tools.getStr(problemObject.getString("code"));
										String problemname = Tools.getStr(problemObject.getString("name"));
										
										//封装工序问题表
										Producescheduleproblem  producescheduleproblem = new Producescheduleproblem();
										producescheduleproblem.setPrisonercode(workmachinelogin.getPrisonercode());
										producescheduleproblem.setPrisonername(workmachinelogin.getPrisonername());
										producescheduleproblem.setLinecode(produceinfo.getLinecode());
										producescheduleproblem.setLinename(produceinfo.getLinename());
										producescheduleproblem.setSectioncode(worklinesectionmachineDemo.getSectioncode());
										Worksection worksection = worksectionDao.findByCode(worklinesectionmachineDemo.getSectioncode());
										if(worksection != null){
											producescheduleproblem.setSectionname(worksection.getName());
										}
										producescheduleproblem.setMachinecode(worklinesectionmachineDemo.getMachinecode());
										producescheduleproblem.setOrdercode(ordercode);
										producescheduleproblem.setOrdername(ordername);
										producescheduleproblem.setProducecode(produceinfo.getProducecode());
										producescheduleproblem.setProductcode(produceinfo.getProductcode());
										producescheduleproblem.setProductname(produceinfo.getProductname());
										producescheduleproblem.setBatchno(sn);
										producescheduleproblem.setDepotamount(1);
										producescheduleproblem.setAddtime(currentTime);
										producescheduleproblem.setStatus("不合格");
										producescheduleproblem.setProblemcode(problemcode);
										producescheduleproblem.setProblemname(problemname);
										producescheduleproblem.setCheckercode(prisonercode);
										producescheduleproblem.setCheckername(prisoner.getPrisonername());
										producescheduleproblemList.add(producescheduleproblem);
										//producesheduleproblemDao.insertSelective(producescheduleproblem);
									}
								}else{
									//回滚
									txManager.rollback(status);
									responseMap.put("code", "201"); //保存失败
									responseMap.put("message", "该产线关联的工位机顺序未配置正确");
									responseMap.put("data", dataMap);
									return responseMap;
								}
							}else{
								//回滚
								txManager.rollback(status);
								responseMap.put("code", "201"); //保存失败
								responseMap.put("message", "该产品关联的工序顺序未配置正确");
								responseMap.put("data", dataMap);
								return responseMap;
							}
						}
					}
				}
				
				//增加生产记录表(包括合格的、不合格的，统统都入库记录生产记录表)
				Worklinesectionmachine worklinesectionmachineDemo = new Worklinesectionmachine();
				worklinesectionmachineDemo.setLinecode(produceinfo.getLinecode());
				List<Worklinesectionmachine> worklinesectionmachineList = worklinesectionmachineDao.findByList(worklinesectionmachineDemo);
				for (Worklinesectionmachine worklinesectionmachine : worklinesectionmachineList) {
					//查询每个工序对应的操作员
					Workmachinelogin workmachinelogin = workmachineloginDao.findLatestLoginerByMachinecode(worklinesectionmachine.getMachinecode());
					if(workmachinelogin == null){
						//回滚
	 					txManager.rollback(status);
	 					responseMap.put("code", "201");//
	 					responseMap.put("message", "产线上还有工位机未登陆过");
	 					responseMap.put("data", dataMap);
	 					return responseMap;
					}
					
					if(workmachinelogin != null){
						//增加合格的产品生产表
						if(leftdepotamount>0){
							Produceschedule produceschedule = new Produceschedule();
							produceschedule.setPrisonercode(workmachinelogin.getPrisonercode());
							produceschedule.setPrisonername(workmachinelogin.getPrisonername());
							produceschedule.setLinecode(produceinfo.getLinecode());
							produceschedule.setLinename(produceinfo.getLinename());
							produceschedule.setSectioncode(worklinesectionmachine.getSectioncode());
							Worksection worksection = worksectionDao.findByCode(worklinesectionmachine.getSectioncode());
							if(worksection != null){
								produceschedule.setSectionname(worksection.getName());
							}
							produceschedule.setMachinecode(worklinesectionmachine.getMachinecode());
							Productworkorder productworkorderdemo = new Productworkorder();
							productworkorderdemo.setProductcode(produceinfo.getProductcode());
							productworkorderdemo.setSerialnumber(worklinesectionmachine.getSerialnumber());
							productworkorderdemo = productworkorderrDao.findByProductcodeAndSerialnumber(productworkorderdemo);
							if(productworkorderdemo != null){
								produceschedule.setOrdercode(productworkorderdemo.getOrdercode());
								produceschedule.setOrdername(productworkorderdemo.getOrdername());
							}
							produceschedule.setProducecode(produceinfo.getProducecode());
							produceschedule.setProductcode(produceinfo.getProductcode());
							produceschedule.setProductname(produceinfo.getProductname());
							produceschedule.setBatchno(produceproduct.getBatchno());
							produceschedule.setDepotamount(leftdepotamount);
							produceschedule.setAddtime(currentTime);
							produceschedule.setStatus("合格");
							produceschedule.setCheckercode(prisonercode);
							produceschedule.setCheckername(prisoner.getPrisonername());
							
							producescheduleList.add(produceschedule);
							//producesheduleDao.insertSelective(produceschedule);
						}
						//增加不合格的产品生产表
						if(qualityNum > 0){
							//有问题的工位机
							if(worklinesectionmachineList_problem != null && worklinesectionmachineList_problem.size() > 0){
								for (Worklinesectionmachine worklinesectionmachine_problem : worklinesectionmachineList_problem) {
									if(worklinesectionmachine.getMachinecode().equals(worklinesectionmachine_problem.getMachinecode())){
										Produceschedule produceschedule = new Produceschedule();
										produceschedule.setPrisonercode(workmachinelogin.getPrisonercode());
										produceschedule.setPrisonername(workmachinelogin.getPrisonername());
										produceschedule.setLinecode(produceinfo.getLinecode());
										produceschedule.setLinename(produceinfo.getLinename());
										produceschedule.setSectioncode(worklinesectionmachine.getSectioncode());
										Worksection worksection = worksectionDao.findByCode(worklinesectionmachine.getSectioncode());
										if(worksection != null){
											produceschedule.setSectionname(worksection.getName());
										}
										produceschedule.setMachinecode(worklinesectionmachine.getMachinecode());
										Productworkorder productworkorderdemo = new Productworkorder();
										productworkorderdemo.setProductcode(produceinfo.getProductcode());
										productworkorderdemo.setSerialnumber(worklinesectionmachine.getSerialnumber());
										productworkorderdemo = productworkorderrDao.findByProductcodeAndSerialnumber(productworkorderdemo);
										if(productworkorderdemo != null){
											produceschedule.setOrdercode(productworkorderdemo.getOrdercode());
											produceschedule.setOrdername(productworkorderdemo.getOrdername());
										}
										produceschedule.setProducecode(produceinfo.getProducecode());
										produceschedule.setProductcode(produceinfo.getProductcode());
										produceschedule.setProductname(produceinfo.getProductname());
										produceschedule.setBatchno(produceproduct.getBatchno());
										produceschedule.setDepotamount(1);
										produceschedule.setAddtime(currentTime);
										produceschedule.setStatus("不合格");
										produceschedule.setCheckercode(prisonercode);
										produceschedule.setCheckername(prisoner.getPrisonername());
										
										producescheduleList.add(produceschedule);
									}else{
										Produceschedule produceschedule = new Produceschedule();
										produceschedule.setPrisonercode(workmachinelogin.getPrisonercode());
										produceschedule.setPrisonername(workmachinelogin.getPrisonername());
										produceschedule.setLinecode(produceinfo.getLinecode());
										produceschedule.setLinename(produceinfo.getLinename());
										produceschedule.setSectioncode(worklinesectionmachine.getSectioncode());
										Worksection worksection = worksectionDao.findByCode(worklinesectionmachine.getSectioncode());
										if(worksection != null){
											produceschedule.setSectionname(worksection.getName());
										}
										produceschedule.setMachinecode(worklinesectionmachine.getMachinecode());
										Productworkorder productworkorderdemo = new Productworkorder();
										productworkorderdemo.setProductcode(produceinfo.getProductcode());
										productworkorderdemo.setSerialnumber(worklinesectionmachine.getSerialnumber());
										productworkorderdemo = productworkorderrDao.findByProductcodeAndSerialnumber(productworkorderdemo);
										if(productworkorderdemo != null){
											produceschedule.setOrdercode(productworkorderdemo.getOrdercode());
											produceschedule.setOrdername(productworkorderdemo.getOrdername());
										}
										produceschedule.setProducecode(produceinfo.getProducecode());
										produceschedule.setProductcode(produceinfo.getProductcode());
										produceschedule.setProductname(produceinfo.getProductname());
										produceschedule.setBatchno(produceproduct.getBatchno());
										produceschedule.setDepotamount(1);
										produceschedule.setAddtime(currentTime);
										produceschedule.setStatus("合格");
										produceschedule.setCheckercode(prisonercode);
										produceschedule.setCheckername(prisoner.getPrisonername());
										
										producescheduleList.add(produceschedule);
									}
								}
							}
						}
					}
				}
				
				//处理质检正常的产品
				if(leftdepotamount > 0){//正常的产品大于0，修改状态，增加工序入库
					produceproduct.setDepotamount(leftdepotamount);
					produceproduct.setProductstatus("生产完成");
					produceproduct.setNfcid(null);//清空NFC卡信息
					produceproduct.setCheckdata(currentTime);
					produceproduct.setCheckercode(prisonercode);
					produceproduct.setCheckername(prisoner.getPrisonername());
					produceproductDao.updateByPrimaryKey(produceproduct);	
					
				}else{//没有正常的产品，删除旧的生产产品信息
					produceproductDao.deleteByPrimaryKey(produceproduct.getId());
				}
				
				//批量插入正常产品的工序
				if(producescheduleList != null && producescheduleList.size() > 0){
					producesheduleDao.saveBatch(producescheduleList);
				}
				
				//批量保存问题工序
				if(producescheduleproblemList != null && producescheduleproblemList.size() > 0){
					producescheduleproblemDao.saveBatch(producescheduleproblemList);
				}
				
				//事务提交
				txManager.commit(status);
				
				responseMap.put("code", "200");
				responseMap.put("message", "处理成功");
				responseMap.put("data", dataMap);
				return responseMap;
				
			}catch(Exception e){
				//回滚
				txManager.rollback(status);
				//输出异常
				e.printStackTrace();
				responseMap.put("code", "201"); //保存失败
				responseMap.put("message", "数据异常，处理失败");
				responseMap.put("data", dataMap);
				return responseMap;
			}
		} 
	}
	
	//上传质检不合格产品通过SN码
	public Map<String, Object> saveUploaddisqualityBySn(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		responseMap.put("message", "获取数据成功");
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		//加锁
		synchronized(lock) {
			//获取配置的事务信息
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
			TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
			
			try{
				String prisonercode = Tools.getStr(jsonObj.getString("token"));
				String sn = Tools.getStr(jsonObj.getString("sn"));
				//当前时间
				String currentTime =  Tools.getCurrentTime();
				//查询生产人员
				Prisoner prisoner = new Prisoner();
				prisoner.setPrisonercode(prisonercode);
				prisoner = prisonerDao.findPrisonerByPrisonercode(prisoner);
				if(prisoner == null){
					
					//回滚
					txManager.rollback(status);
					
					responseMap.put("code", "201");//
					responseMap.put("message", "该质检人员不存在");//
					responseMap.put("data", dataMap);
					return responseMap;
				}
				
				//查询生产产品信息
				Produceproduct produceproduct = produceproductDao.findByBatchno(sn);
				if(produceproduct == null){
					//回滚
					txManager.rollback(status);
					responseMap.put("code", "201");//
					responseMap.put("message", "该SN码未绑定任何产品信息");//
					responseMap.put("data", dataMap);
					return responseMap;
				}
				
				if(!"生产中".equals(produceproduct.getProductstatus()) && !"待返工".equals(produceproduct.getProductstatus())){
					//回滚
					txManager.rollback(status);
					responseMap.put("code", "201");//
					responseMap.put("message", "该SN码绑定的产品不是生产状态，不能进行质检!");//
					responseMap.put("data", dataMap);
					return responseMap;
				}
				
				//查询产线信息
				Produceinfo produceinfo = produceinfoDao.findByProducecode(produceproduct.getProducecode());
				if(produceinfo == null){
					//回滚
					txManager.rollback(status);
					responseMap.put("code", "201");//
					responseMap.put("message", "该SN码关联的产线不存在");//
					responseMap.put("data", dataMap);
					return responseMap;
				}
				
				//封装质检不合格产品工序问题LIST,批量插入数据用
				ArrayList<Producescheduleproblem> producescheduleproblemList = new ArrayList<Producescheduleproblem>();
				//封装正常产品的工序LIST,批量插入数据用
				ArrayList<Produceschedule> producescheduleList = new ArrayList<Produceschedule>();
				
				//封装有问题的工位机
				ArrayList<Worklinesectionmachine> worklinesectionmachineList_problem = new ArrayList<Worklinesectionmachine>();
				
				//该包原来的总件数
				int leftdepotamount = produceproduct.getDepotamount();
				//有质量问题的包数
				int qualityNum = 0;
				//质量信息
				JSONObject disqualitydataObject = jsonObj.getJSONObject("disqualitydata");
				//产品问题
				JSONArray datalistArray = disqualitydataObject.getJSONArray("datalist");
				
				//有质量问题的产品,必须要重新分包
				if(datalistArray != null && datalistArray.length() > 0){
					//有质量问题的包数
					qualityNum = datalistArray.length();
					//正常产品数量
					leftdepotamount = leftdepotamount - qualityNum;
						
					//循环有问题的产品包数
					for (int i = 0; i < qualityNum; i++) {
						JSONObject disqualityinfo = datalistArray.getJSONObject(i);
						
						//String packagenum = Tools.getStr(disqualityinfo.getString("package"));
						//String disqualitynumber = Tools.getStr(disqualityinfo.getString("disqualitynumber"));
						//String sn = Tools.getStr(disqualityinfo.getString("sn"));
						//将有问题的产品拆分入库
						//String batchno = productdepotService.getProductbatchno(produceproduct.getProductcode());
						Produceproduct produceproductProblem = new Produceproduct();
						produceproductProblem.setProducecode(produceproduct.getProducecode());
						produceproductProblem.setProductcode(produceproduct.getProductcode());
						produceproductProblem.setProductname(produceproduct.getProductname());
						produceproductProblem.setBatchno(sn);
						produceproductProblem.setDepotamount(1);
						produceproductProblem.setProductstatus("待返工");
						produceproductProblem.setPrintflag("未打印");
						produceproductProblem.setAddtime(produceproduct.getAddtime());
						produceproductProblem.setNfcid(null);
						produceproductProblem.setCheckdata(null);
						produceproductProblem.setCheckercode(null);
						produceproductProblem.setCheckername(null);
						produceproductDao.insert(produceproductProblem);
						
						//问题工序列表
						JSONArray disqualityproblem = disqualityinfo.getJSONArray("disqualityproblem");
						
						for (int j = 0; j < disqualityproblem.length(); j++) {
							JSONObject orderinfo = disqualityproblem.getJSONObject(j);
							String ordercode = Tools.getStr(orderinfo.getString("ordercode"));
							String ordername = Tools.getStr(orderinfo.getString("ordername"));
							
							//查找该工序对应的位置
							Productworkorder productworkorder = new Productworkorder();
							productworkorder.setProductcode(produceinfo.getProductcode());
							productworkorder.setOrdercode(ordercode);
							productworkorder = productworkorderDao.findByProductcodeAndOrdercode(productworkorder);
							
							if(productworkorder != null){
								//查询该工序对应的工位机
								Worklinesectionmachine worklinesectionmachineDemo = new Worklinesectionmachine();
								worklinesectionmachineDemo.setLinecode(produceinfo.getLinecode());
								worklinesectionmachineDemo.setSerialnumber(productworkorder.getSerialnumber());
								worklinesectionmachineDemo = worklinesectionmachineDao.findByLinecodeAndSerialnumber(worklinesectionmachineDemo);
								if(worklinesectionmachineDemo != null){
									
									//将有问题的工位机保存到临时缓存中，后面单独处理
									worklinesectionmachineList_problem.add(worklinesectionmachineDemo);
									
									//查询每个工序对应的当前生产人员
									Workmachinelogin workmachinelogin = workmachineloginDao.findLatestLoginerByMachinecode(worklinesectionmachineDemo.getMachinecode());
									if(workmachinelogin == null){
										//回滚
					 					txManager.rollback(status);
					 					responseMap.put("code", "201");//
					 					responseMap.put("message", "产线上还有工位机未登录过");
					 					responseMap.put("data", dataMap);
					 					return responseMap;
									}
									//问题列表
									JSONArray problemArray = orderinfo.getJSONArray("problem");
									for (int k = 0; k < problemArray.length(); k++) {
										JSONObject problemObject = problemArray.getJSONObject(k);
										String problemcode = Tools.getStr(problemObject.getString("code"));
										String problemname = Tools.getStr(problemObject.getString("name"));
										
										//封装工序问题表
										Producescheduleproblem  producescheduleproblem = new Producescheduleproblem();
										producescheduleproblem.setPrisonercode(workmachinelogin.getPrisonercode());
										producescheduleproblem.setPrisonername(workmachinelogin.getPrisonername());
										producescheduleproblem.setLinecode(produceinfo.getLinecode());
										producescheduleproblem.setLinename(produceinfo.getLinename());
										producescheduleproblem.setSectioncode(worklinesectionmachineDemo.getSectioncode());
										Worksection worksection = worksectionDao.findByCode(worklinesectionmachineDemo.getSectioncode());
										if(worksection != null){
											producescheduleproblem.setSectionname(worksection.getName());
										}
										producescheduleproblem.setMachinecode(worklinesectionmachineDemo.getMachinecode());
										producescheduleproblem.setOrdercode(ordercode);
										producescheduleproblem.setOrdername(ordername);
										producescheduleproblem.setProducecode(produceinfo.getProducecode());
										producescheduleproblem.setProductcode(produceinfo.getProductcode());
										producescheduleproblem.setProductname(produceinfo.getProductname());
										producescheduleproblem.setBatchno(sn);
										producescheduleproblem.setDepotamount(1);
										producescheduleproblem.setAddtime(currentTime);
										producescheduleproblem.setStatus("不合格");
										producescheduleproblem.setProblemcode(problemcode);
										producescheduleproblem.setProblemname(problemname);
										producescheduleproblem.setCheckercode(prisonercode);
										producescheduleproblem.setCheckername(prisoner.getPrisonername());
										producescheduleproblemList.add(producescheduleproblem);
										//producesheduleproblemDao.insertSelective(producescheduleproblem);
									}
								}else{
									//回滚
									txManager.rollback(status);
									responseMap.put("code", "201"); //保存失败
									responseMap.put("message", "该产线关联的工位机顺序未配置正确");
									responseMap.put("data", dataMap);
									return responseMap;
								}
							}else{
								//回滚
								txManager.rollback(status);
								responseMap.put("code", "201"); //保存失败
								responseMap.put("message", "该产品关联的工序顺序未配置正确");
								responseMap.put("data", dataMap);
								return responseMap;
							}
						}
					}
				}
				
				//增加生产记录表(包括合格的、不合格的，统统都入库记录生产记录表)
				Worklinesectionmachine worklinesectionmachineDemo = new Worklinesectionmachine();
				worklinesectionmachineDemo.setLinecode(produceinfo.getLinecode());
				List<Worklinesectionmachine> worklinesectionmachineList = worklinesectionmachineDao.findByList(worklinesectionmachineDemo);
				for (Worklinesectionmachine worklinesectionmachine : worklinesectionmachineList) {
					//查询每个工序对应的操作员
					Workmachinelogin workmachinelogin = workmachineloginDao.findLatestLoginerByMachinecode(worklinesectionmachine.getMachinecode());
					if(workmachinelogin == null){
						//回滚
	 					txManager.rollback(status);
	 					responseMap.put("code", "201");//
	 					responseMap.put("message", "产线上还有工位机未登录过");
	 					responseMap.put("data", dataMap);
	 					return responseMap;
					}
					
					if(workmachinelogin != null){
						//增加合格的产品生产表
						if(leftdepotamount>0){
							Produceschedule produceschedule = new Produceschedule();
							produceschedule.setPrisonercode(workmachinelogin.getPrisonercode());
							produceschedule.setPrisonername(workmachinelogin.getPrisonername());
							produceschedule.setLinecode(produceinfo.getLinecode());
							produceschedule.setLinename(produceinfo.getLinename());
							produceschedule.setSectioncode(worklinesectionmachine.getSectioncode());
							Worksection worksection = worksectionDao.findByCode(worklinesectionmachine.getSectioncode());
							if(worksection != null){
								produceschedule.setSectionname(worksection.getName());
							}
							produceschedule.setMachinecode(worklinesectionmachine.getMachinecode());
							Productworkorder productworkorderdemo = new Productworkorder();
							productworkorderdemo.setProductcode(produceinfo.getProductcode());
							productworkorderdemo.setSerialnumber(worklinesectionmachine.getSerialnumber());
							productworkorderdemo = productworkorderrDao.findByProductcodeAndSerialnumber(productworkorderdemo);
							if(productworkorderdemo != null){
								produceschedule.setOrdercode(productworkorderdemo.getOrdercode());
								produceschedule.setOrdername(productworkorderdemo.getOrdername());
							}
							produceschedule.setProducecode(produceinfo.getProducecode());
							produceschedule.setProductcode(produceinfo.getProductcode());
							produceschedule.setProductname(produceinfo.getProductname());
							produceschedule.setBatchno(produceproduct.getBatchno());
							produceschedule.setDepotamount(leftdepotamount);
							produceschedule.setAddtime(currentTime);
							produceschedule.setStatus("合格");
							produceschedule.setCheckercode(prisonercode);
							produceschedule.setCheckername(prisoner.getPrisonername());
							
							producescheduleList.add(produceschedule);
							//producesheduleDao.insertSelective(produceschedule);
						}
						//增加不合格的产品生产表
						if(qualityNum > 0){
							//有问题的工位机
							if(worklinesectionmachineList_problem != null && worklinesectionmachineList_problem.size() > 0){
								for (Worklinesectionmachine worklinesectionmachine_problem : worklinesectionmachineList_problem) {
									if(worklinesectionmachine.getMachinecode().equals(worklinesectionmachine_problem.getMachinecode())){
										Produceschedule produceschedule = new Produceschedule();
										produceschedule.setPrisonercode(workmachinelogin.getPrisonercode());
										produceschedule.setPrisonername(workmachinelogin.getPrisonername());
										produceschedule.setLinecode(produceinfo.getLinecode());
										produceschedule.setLinename(produceinfo.getLinename());
										produceschedule.setSectioncode(worklinesectionmachine.getSectioncode());
										Worksection worksection = worksectionDao.findByCode(worklinesectionmachine.getSectioncode());
										if(worksection != null){
											produceschedule.setSectionname(worksection.getName());
										}
										produceschedule.setMachinecode(worklinesectionmachine.getMachinecode());
										Productworkorder productworkorderdemo = new Productworkorder();
										productworkorderdemo.setProductcode(produceinfo.getProductcode());
										productworkorderdemo.setSerialnumber(worklinesectionmachine.getSerialnumber());
										productworkorderdemo = productworkorderrDao.findByProductcodeAndSerialnumber(productworkorderdemo);
										if(productworkorderdemo != null){
											produceschedule.setOrdercode(productworkorderdemo.getOrdercode());
											produceschedule.setOrdername(productworkorderdemo.getOrdername());
										}
										produceschedule.setProducecode(produceinfo.getProducecode());
										produceschedule.setProductcode(produceinfo.getProductcode());
										produceschedule.setProductname(produceinfo.getProductname());
										produceschedule.setBatchno(produceproduct.getBatchno());
										produceschedule.setDepotamount(1);
										produceschedule.setAddtime(currentTime);
										produceschedule.setStatus("不合格");
										produceschedule.setCheckercode(prisonercode);
										produceschedule.setCheckername(prisoner.getPrisonername());
										
										producescheduleList.add(produceschedule);
									}else{
										Produceschedule produceschedule = new Produceschedule();
										produceschedule.setPrisonercode(workmachinelogin.getPrisonercode());
										produceschedule.setPrisonername(workmachinelogin.getPrisonername());
										produceschedule.setLinecode(produceinfo.getLinecode());
										produceschedule.setLinename(produceinfo.getLinename());
										produceschedule.setSectioncode(worklinesectionmachine.getSectioncode());
										Worksection worksection = worksectionDao.findByCode(worklinesectionmachine.getSectioncode());
										if(worksection != null){
											produceschedule.setSectionname(worksection.getName());
										}
										produceschedule.setMachinecode(worklinesectionmachine.getMachinecode());
										Productworkorder productworkorderdemo = new Productworkorder();
										productworkorderdemo.setProductcode(produceinfo.getProductcode());
										productworkorderdemo.setSerialnumber(worklinesectionmachine.getSerialnumber());
										productworkorderdemo = productworkorderrDao.findByProductcodeAndSerialnumber(productworkorderdemo);
										if(productworkorderdemo != null){
											produceschedule.setOrdercode(productworkorderdemo.getOrdercode());
											produceschedule.setOrdername(productworkorderdemo.getOrdername());
										}
										produceschedule.setProducecode(produceinfo.getProducecode());
										produceschedule.setProductcode(produceinfo.getProductcode());
										produceschedule.setProductname(produceinfo.getProductname());
										produceschedule.setBatchno(produceproduct.getBatchno());
										produceschedule.setDepotamount(1);
										produceschedule.setAddtime(currentTime);
										produceschedule.setStatus("合格");
										produceschedule.setCheckercode(prisonercode);
										produceschedule.setCheckername(prisoner.getPrisonername());
										
										producescheduleList.add(produceschedule);
									}
								}
							}
						}
					}
				}
				
				//处理质检正常的产品
				if(leftdepotamount > 0){//正常的产品大于0，修改状态，增加工序入库
					produceproduct.setDepotamount(leftdepotamount);
					produceproduct.setProductstatus("生产完成");
					produceproduct.setNfcid(null);//清空NFC卡信息
					produceproduct.setCheckdata(currentTime);
					produceproduct.setCheckercode(prisonercode);
					produceproduct.setCheckername(prisoner.getPrisonername());
					produceproductDao.updateByPrimaryKey(produceproduct);	
				}else{//没有正常的产品，删除旧的生产产品信息
					produceproductDao.deleteByPrimaryKey(produceproduct.getId());
				}
				
				//批量插入生产记录表
				if(producescheduleList != null && producescheduleList.size() >0){
					producesheduleDao.saveBatch(producescheduleList);
				}
				
				//批量插入质检不合格的产品工序的问题
				if(producescheduleproblemList != null && producescheduleproblemList.size() > 0){
					producescheduleproblemDao.saveBatch(producescheduleproblemList);
				}
				
				//事务提交
				txManager.commit(status);
				
				responseMap.put("code", "200");
				responseMap.put("message", "上传数据成功");
				responseMap.put("data", dataMap);
				
				return responseMap;
			}catch(Exception e){
				//回滚
				txManager.rollback(status);
				//输出异常
				e.printStackTrace();
				responseMap.put("code", "201"); //保存失败
				responseMap.put("result", "数据异常，处理失败");
				return responseMap;
			}
		} 
	}
	
	//获取配置的质检记录查询条件
	public Map<String, Object> getconditioncfg(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		responseMap.put("message", "获取数据成功");
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		//String prisonercode = Tools.getStr(jsonObj.getString("token"));

		 String linecode = Tools.getStr(jsonObj.getString("linecode"));
		HashMap<String, Object> allMap = new HashMap<String, Object>();
		
		//产品类型
		List<HashMap<String, Object>> productList = new ArrayList<HashMap<String, Object>>();
		//xxq 根据产线代码返回当前产线上的信息
		List<Product> productlist = productDao.findByLineCode(linecode);


		for (Product product : productlist) {
			HashMap<String, Object> productMap = new HashMap<String, Object>();
			productMap.put("code", product.getProductcode());
			productMap.put("name", product.getProductname());
			productList.add(productMap);
		}
		dataMap.put("product", productList);


		//质检问题
		List<HashMap<String, Object>> problemList = new ArrayList<HashMap<String, Object>>();


		//xxq 根据产线代码获取当前产线上的工序列表
		List<HashMap<String, Object>> workorderList = new ArrayList<HashMap<String, Object>>();
		List<Workorder> workorderlist = workorderDao.findWorkorderByLineCode(linecode);


		//xxq 根据产线代码获取当前产线上的所有产品的质检问题列表
		List<Problem> problemlist = problemDao.findProblemlistByLineCode(linecode);
		for (Problem problem : problemlist) {
			HashMap<String, Object> problemMap = new HashMap<String, Object>();
			problemMap.put("code", problem.getProblemcode());
			problemMap.put("name", problem.getProblemname());
			problemList.add(problemMap);
		}
		dataMap.put("qrproblem", problemList);




		for (Workorder workorder : workorderlist) {
			HashMap<String, Object> workorderMap = new HashMap<String, Object>();
			workorderMap.put("code", workorder.getOrdercode());
			workorderMap.put("name", workorder.getOrdername());
			workorderList.add(workorderMap);
		}
		dataMap.put("workorder", workorderList);
		
		responseMap.put("data", dataMap);
		
		return responseMap;
	}

	//获取配置的质检历史记录
	public Map<String, Object> gethistoryrecords(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		responseMap.put("message", "获取数据成功");
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String prisonercode = Tools.getStr(jsonObj.getString("token"));
		
		//条件
		JSONObject condition = jsonObj.getJSONObject("condition");
		String productcode = Tools.getStr(condition.getString("typenumber"));
		String batchno = Tools.getStr(condition.getString("batch"));
		String problemcode = Tools.getStr(condition.getString("code"));
		String linecode = Tools.getStr(condition.getString("linecode"));
		//String name = Tools.getStr(condition.getString("name"));
		//工序
		String workorder = Tools.getStr(condition.getString("workorder"));
		
		String startdate = Tools.getStr(condition.getString("startdate"));
		String enddate = Tools.getStr(condition.getString("enddate"));
		String pagestart = Tools.getStr(condition.getString("pagestart"));
		String limit = Tools.getStr(condition.getString("limit"));
		
		//当前页 
		int page = Integer.parseInt(pagestart) /Integer.parseInt(limit) + 1 ;
		Producescheduleproblem record = new Producescheduleproblem();
		record.setProductcode(productcode);
		record.setBatchno(batchno);
		record.setProblemcode(problemcode);
		record.setBegintime(startdate);
		record.setEndtime(enddate);
		record.setOrdercode(workorder);
		record.setPage(page);
		record.setLimit(Integer.parseInt(limit));
		record.setLinecode(linecode);
		//封装当前的质检员
		//record.setCheckercode(prisonercode);
		//产品类型
		List<HashMap<String, Object>> datalist = new ArrayList<HashMap<String, Object>>();
		
		Integer total = producescheduleproblemDao.findByCount(record);
		List<Producescheduleproblem> producescheduleproblemList = producescheduleproblemDao.findByListForPage(record);

		for (Producescheduleproblem producescheduleproblem : producescheduleproblemList) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			//产品型号
			objectMap.put("typenumber", producescheduleproblem.getProductname());
			//生产任务号
			objectMap.put("ordernumber", producescheduleproblem.getProducecode());
			//批次号
			objectMap.put("batch", producescheduleproblem.getBatchno());
			//问题编号
			objectMap.put("code", producescheduleproblem.getProblemcode());
			//问题名称
			objectMap.put("name", producescheduleproblem.getProblemname());
			//SN码
			objectMap.put("sn", producescheduleproblem.getBatchno());
			//质检时间
			objectMap.put("time", StringUtils.isEmpty(producescheduleproblem.getAddtime())?"":Tools.getStr(producescheduleproblem.getAddtime()).substring(0, 19));
			//工段
			objectMap.put("worksection", producescheduleproblem.getSectionname());
			//工位
			objectMap.put("workstation", producescheduleproblem.getMachinecode());
			//犯人编号
			objectMap.put("prisonercode", producescheduleproblem.getPrisonercode());
			//犯人姓名
			objectMap.put("prisonername", producescheduleproblem.getPrisonername());
			//质检员编号
			objectMap.put("checkercode", producescheduleproblem.getCheckercode());
			//质检员姓名
			objectMap.put("checkername", producescheduleproblem.getCheckername());
			
			datalist.add(objectMap);
		}
		
		dataMap.put("datalist", datalist);
		dataMap.put("pagestart", pagestart);
		dataMap.put("limit", limit);
		dataMap.put("total", total);
		responseMap.put("data", dataMap);
		
		return responseMap;
	}
	
	//获取产品批次号Batch
	public Map<String, Object> getSn(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		responseMap.put("message", "获取数据成功");
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String prisonercode = Tools.getStr(jsonObj.getString("token"));
		String productcode = Tools.getStr(jsonObj.getString("productcode"));
		String packagenumber = Tools.getStr(jsonObj.getString("package")); //件数
		String sn = productdepotService.getProductbatchno(productcode);
			
		dataMap.put("sn", sn);
		dataMap.put("productcode", productcode);
		dataMap.put("package", packagenumber);
		responseMap.put("data", dataMap);
		
		return responseMap;
	}
	
	//退出登录
	public Map<String, Object> exit(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String prisonercode = Tools.getStr(jsonObj.getString("token"));
		
		responseMap.put("code", "200");
		responseMap.put("message", "退出成功");
		responseMap.put("data", dataMap);
		
		return responseMap;
	}
	
	//指纹打卡
	public Map<String, Object> saveUploadRollcallinfo(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		String uuid = Tools.getStr(jsonObj.getString("uuid"));
		String prisonercode = Tools.getStr(jsonObj.getString("prisonercode"));
		String machinecode = Tools.getStr(jsonObj.getString("machinecode"));
		
		Rollcall rollcall = rollcallDao.findByUuid(uuid);
		if(rollcall == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "上传失败，打卡UUID错误");//
			return responseMap;
		}
		
		//封装登录信息
		Prisoner record = new Prisoner();
		record.setPrisonercode(prisonercode);
		Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(record);
		
		if(prisoner == null){
			responseMap.put("code", "201");//
			responseMap.put("message", "人员编号错误");//
			return responseMap;
		}
		
		
		Rollcallinfo rollcallinfo = new Rollcallinfo();
		rollcallinfo.setUuid(uuid);
		rollcallinfo.setPrisonercode(prisonercode);
		rollcallinfo = rollcallinfoDao.findByUuidAndPrisonercode(rollcallinfo);
		if(rollcallinfo != null){
			rollcallinfo.setAddtime(Tools.getCurrentTime());
			rollcallinfo.setStatus("已签到");
			rollcallinfo.setMachinecode(machinecode);
			rollcallinfoDao.updateByPrimaryKeySelective(rollcallinfo);
		}
		
		responseMap.put("code", "200");
		responseMap.put("message", "指纹打卡成功");
		
		return responseMap;
	}
	
	/**
	 * 查询大屏显示数据Json
	 */
	public Map<String, Object> findBigscreanshowData(JSONObject jsonObj) {
		//封装JSon的Map
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		//生产统计
		List<HashMap<String, Object>> paiminglist = new ArrayList<HashMap<String, Object>>();
		//问题统计
		List<HashMap<String, Object>> problemlist = new ArrayList<HashMap<String, Object>>();
		
		List<Workline> worklineList = worklineDao.findByList(new Workline());
		for (int i = 0; i < worklineList.size(); i++) {
			//生产计划
			HashMap<String, Object> paimingMap = new HashMap<String, Object>();
			//序号
			paimingMap.put("ranking", i+1);
			//产线名称
			paimingMap.put("line", worklineList.get(i).getName());
			//当天生产完成量
			Integer completedCount = produceproductDao.findCompletedCountByLinecode(worklineList.get(i).getCode());
			if(completedCount == null){
				completedCount= 0;
			}
			//当天的合格产量
			paimingMap.put("qualified", completedCount);
			//当天之前未完成量
			Integer incompletedCount = produceproductDao.findIncompletedCountByLinecode(worklineList.get(i).getCode());
			if(incompletedCount == null){
				incompletedCount= 0;
			}
			//当天报废量
			Integer wastedCount = produceproductDao.findWastedCountByLinecode(worklineList.get(i).getCode());
			if(wastedCount == null){
				wastedCount= 0;
			}
			//当天的计划量= 当天生产完成量 + 当天之前未完成量 + 当天报废量
			int planCount = completedCount + incompletedCount + wastedCount ;
			paimingMap.put("plan", planCount);
			
			//合格率
			if(planCount == 0){
				paimingMap.put("CompletionRate", Tools.getPercentage(0));
			}else{
				paimingMap.put("CompletionRate", Tools.getPercentage((float)completedCount/(float)planCount));
			}
			paiminglist.add(paimingMap);
		}
		//封装产线生产统计
		responseMap.put("workshop_paiming", paiminglist);
		
		//分组查询各问题数量
		Producescheduleproblem record = new Producescheduleproblem();
		record.setAddtime(Tools.getCurrentTime());//查询当天
		List<Producescheduleproblem> ProblemCountList = producescheduleproblemDao.findProblemCountByGrouping(record);
		for (Producescheduleproblem producescheduleproblem : ProblemCountList) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			objectMap.put("type", producescheduleproblem.getProblemname());
			objectMap.put("value", producescheduleproblem.getDepotamount());
			problemlist.add(objectMap);
		}
		//封装问题
		responseMap.put("workshop_problem", problemlist);
				
		return responseMap;
	}
	
	/**
	 * 查询小屏显示数据Json
	 */
	public Map<String, Object> findSmallscreanshowData(JSONObject jsonObj) {
		//封装JSon的Map
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("code", "200");
		//生产统计
		List<HashMap<String, Object>> paiminglist = new ArrayList<HashMap<String, Object>>();
		//问题统计
		List<HashMap<String, Object>> problemlist = new ArrayList<HashMap<String, Object>>();
		
		String linecode = Tools.getStr(jsonObj.getString("linecode"));
		if(StringUtils.isEmpty(linecode)){
			responseMap.put("code", "201");//
			responseMap.put("message", "请求失败，请输入产线编号");//
			return responseMap;
		}
		
		//当天实际
		String cuurenttime = Tools.getCurrentTime();
		
		//当天生产完成量
		Integer completedCount = produceproductDao.findCompletedCountByLinecode(linecode);
		if(completedCount == null){
			completedCount= 0;
		}
		//当天之前未完成量
		Integer incompletedCount = produceproductDao.findIncompletedCountByLinecode(linecode);
		if(incompletedCount == null){
			incompletedCount= 0;
		}
		//当天报废量
		Integer wastedCount = produceproductDao.findWastedCountByLinecode(linecode);
		if(wastedCount == null){
			wastedCount= 0;
		}
		//当天的计划量= 当天生产完成量 + 当天之前未完成量 + 当天报废量
		int planCount = completedCount + incompletedCount + wastedCount;
		
		Workmachinelogin record = new Workmachinelogin();
		record.setLinecode(linecode);
		List<Workmachinelogin> workmachineloginList =  workmachineloginDao.findCurrentDayLoginByListForPage(record);
		for (int i = 0; i < workmachineloginList.size(); i++) {
			//生产计划
			HashMap<String, Object> paimingMap = new HashMap<String, Object>();
			//序号
			paimingMap.put("ranking", i+1);
			//产线名称
			paimingMap.put("name", workmachineloginList.get(i).getPrisonername());
			//当天计划量
			paimingMap.put("plan", planCount);
			//当天的生产次数
			Produceschedule produceschedule = new Produceschedule();
			produceschedule.setLinecode(linecode);
			produceschedule.setPrisonercode(workmachineloginList.get(i).getPrisonercode());
			produceschedule.setAddtime(cuurenttime);
			int produceCount = producesheduleDao.findProducedCountByPrisonercode(produceschedule);
			//当天的合格产量
			produceschedule.setStatus("合格");
			int qualifiedCount = producesheduleDao.findProducedCountByPrisonercode(produceschedule);
			paimingMap.put("qualified", qualifiedCount);
			//返工数
			produceschedule.setStatus("不合格");
			int problemCount = producesheduleDao.findProducedCountByPrisonercode(produceschedule);
			paimingMap.put("counter", problemCount);
			//返工率
			if(produceCount == 0){
				paimingMap.put("rate", Tools.getPercentage(0));
			}else{
				paimingMap.put("rate", Tools.getPercentage((float)problemCount/(float)produceCount));
			}
			paiminglist.add(paimingMap);
		}
		
		//封装产线生产统计
		responseMap.put("line_paiming", paiminglist);
		
		//分组查询各问题数量
		Producescheduleproblem recard = new Producescheduleproblem();
		recard.setLinecode(linecode);
		recard.setAddtime(cuurenttime);
		List<Producescheduleproblem> ProblemCountList = producescheduleproblemDao.findProblemCountByGrouping(recard);
		for (Producescheduleproblem producescheduleproblem : ProblemCountList) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			objectMap.put("type", producescheduleproblem.getProblemname());
			objectMap.put("value", producescheduleproblem.getDepotamount());
			problemlist.add(objectMap);
		}
		//封装问题
		responseMap.put("line_problem", problemlist);
		return responseMap;
	}
	
	// 保存工具领用
	public Map<String, Object> saveBorrowTool (JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		//加锁
		synchronized(lock) {
			//获取配置的事务信息
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
			TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
			
			try{
		
				String prisonercode = Tools.getStr(jsonObj.getString("prisonercode"));
				JSONArray datalist = jsonObj.getJSONArray("datalist");
				for (int i = 0; i < datalist.length(); i++) {
					JSONObject toolinfo = datalist.getJSONObject(i);
					String toolcode = Tools.getStr(toolinfo.getString("toolcode"));
					String num = Tools.getStr(toolinfo.getString("num"));
					//查询工具库 存不存在此种产品
					Toolplate toolplate = toolplateDao.findByToolcode(toolcode);
					if(toolplate == null){
						responseMap.put("code", "201");//
						responseMap.put("message", "操作失败，存放此工具的工具版不存在");//
						responseMap.put("data", dataMap);
						//回滚
						txManager.rollback(status);
						return responseMap;
					}
					
					//已有库存量
					int leftnum = toolplate.getLeftnum();
					//本次领用量
					int inoutamount = Integer.parseInt(num);
					
					if(leftnum == 0){
						responseMap.put("code", "201");//
						responseMap.put("message", "操作失败，此工具版没有剩余工具可领用！");//
						responseMap.put("data", dataMap);
						//回滚
						txManager.rollback(status);
						return responseMap;
					}
					
					//领用量不能大于仓库剩余数
					if(leftnum-inoutamount < 0){
						responseMap.put("code", "201");//
						responseMap.put("message", "操作失败，领用数量不能大于库存量！");//
						responseMap.put("data", dataMap);
						//回滚
						txManager.rollback(status);
						return responseMap;
					}
					
					//修改该工具库存量
					//更新剩余量
					toolplate.setLeftnum(leftnum-inoutamount);
					//更新借出量
					toolplate.setOutnum(toolplate.getOutnum() + inoutamount);
					toolplateDao.updateByPrimaryKeySelective(toolplate);
					
					//增加工具领用记录
					Toolinout toolinout = new Toolinout();
					toolinout.setToolcode(toolcode);
					toolinout.setToolname(toolplate.getToolname());
					//toolinout.setOperatorcode(operator.getLoginname());
					toolinout.setInoutamount(inoutamount);
					toolinout.setUsetime(Tools.getCurrentTime());
					toolinout.setInoutstatus("领用");
					Prisoner prisoner = new Prisoner();
					prisoner.setPrisonercode(prisonercode);
					prisoner = prisonerDao.findPrisonerByPrisonercode(prisoner);
					if(prisoner != null){
						toolinout.setInoutername(prisoner.getPrisonername());
					}
					toolinout.setDepotrackcode(toolplate.getToolplatecode());
					toolinoutDao.insertSelective(toolinout);
				}
				
				responseMap.put("code", "200");
				responseMap.put("message", "操作成功");
				responseMap.put("data", dataMap);
				//事务提交
				txManager.commit(status);
				return responseMap;
			
			}catch(Exception e){
				//回滚
				txManager.rollback(status);
				//输出异常
				e.printStackTrace();
				responseMap.put("code", "201"); //保存失败
				responseMap.put("result", "数据异常，处理失败");
				return responseMap;
			}
		} 
	}
	
	
	// 保存工具归还
	public Map<String, Object> saveReturnTool(JSONObject jsonObj) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		
		//封装数据
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		
		//加锁
		synchronized(lock) {
			//获取配置的事务信息
			DefaultTransactionDefinition def = new DefaultTransactionDefinition();
			def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
			TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
			
			try{
		
				String prisonercode = Tools.getStr(jsonObj.getString("prisonercode"));
				JSONArray datalist = jsonObj.getJSONArray("datalist");
				for (int i = 0; i < datalist.length(); i++) {
					JSONObject toolinfo = datalist.getJSONObject(i);
					String toolcode = Tools.getStr(toolinfo.getString("toolcode"));
					String num = Tools.getStr(toolinfo.getString("num"));
					
					Toolinout toolinout = new Toolinout();
					toolinout.setToolcode(toolcode);
					toolinout.setInoutamount(Integer.parseInt(num));
					toolinout.setInoutstatus("领用");
					Toolinout inout = toolinoutDao.findUnreturnByToolcodeAndInoutamount(toolinout);
					if(inout == null){
						responseMap.put("code", "201");//
						responseMap.put("message", "操作失败，没有找到该工具相同借用数量的记录！");//
						responseMap.put("data", dataMap);
						//回滚
						txManager.rollback(status);
						return responseMap;
					}
					
					inout.setInoutstatus("归还"); //无库存
					inout.setReturntime(Tools.getCurrentTime());//归还时间
					toolinoutDao.updateByPrimaryKeySelective(inout);
					//增加工具库存
					Toolplate toolplate = toolplateDao.findByToolcode(toolcode);
					toolplate.setLeftnum(toolplate.getLeftnum() + inout.getInoutamount());
					toolplate.setOutnum(toolplate.getOutnum()-inout.getInoutamount());
					toolplateDao.updateByPrimaryKeySelective(toolplate);
				}
				
				responseMap.put("code", "200");
				responseMap.put("message", "操作成功");
				responseMap.put("data", dataMap);
				//事务提交
				txManager.commit(status);
				return responseMap;
			
			}catch(Exception e){
				//回滚
				txManager.rollback(status);
				//输出异常
				e.printStackTrace();
				responseMap.put("code", "201"); //保存失败
				responseMap.put("result", "数据异常，处理失败");
				return responseMap;
			}
		} 
	}
	
	
}
